package com.pets.controller;

import com.pets.dao.KnowledgeMapper;
import com.pets.entity.Knowledge;
import com.pets.qo.TestUploadQO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

/**
 *文件上传
 */
@Controller
public class FileUploadController {

    @Resource
    private KnowledgeMapper knowledgeMapper;

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public  String uploadFileHandler(TestUploadQO  qo) {
        MultipartFile file =qo.getFile();
        Knowledge knowledge = knowledgeMapper.selectByPrimaryKey(1);
        if (!file.isEmpty()) {
            try {
                // 文件存放服务端的位置
                String rootPath = "D:\\tmp\\upload";
                File dir = new File(rootPath + File.separator );
                if (!dir.exists())
                    dir.mkdirs();
                // 写文件到服务器
                File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename());
                file.transferTo(serverFile);
                knowledge.setKpicture("/upload/"+file.getOriginalFilename());
                knowledgeMapper.updateByPrimaryKey(knowledge);
                return "You successfully uploaded file=" +  file.getOriginalFilename();
            } catch (Exception e) {
                return "You failed to upload " +  file.getOriginalFilename() + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " +  file.getOriginalFilename() + " because the file was empty.";
        }
    }
}
